﻿using Microsoft.VisualStudio.GraphModel.CodeSchema;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
using VSAdditionalCommands.Helpers;
using static System.Net.Mime.MediaTypeNames;

namespace VSAdditionalCommands.ToolWindows.ReplaceKeepCaseToolWindow
{
    public partial class ReplaceKeepCaseToolWindowControl : UserControl
    {
        public ReplaceKeepCaseToolWindowControl()
        {
            this.InitializeComponent();
        }

        private void btnReplace_Click(object sender, RoutedEventArgs e)
        {
            int pos = 0;
            do
            {
                DocumentView docView = VS.Documents.GetActiveDocumentViewAsync().Result;
                if (docView?.TextView == null
                    || docView.TextView.Selection.SelectedSpans.Count == 0
                    || docView.TextBuffer == null) return;
                var span = docView.TextView.Selection.SelectedSpans[0];
                var snapshot = docView.TextBuffer.CurrentSnapshot;

                var text = snapshot.GetText(span.Start, span.Length);
                pos = text.IndexOf(txtFind.Text, pos, StringComparison.OrdinalIgnoreCase);
                if (pos < 0)
                {
                    break;
                }
                else
                {
                    //замена с сохранением регистра первой буквы например: замена base на concrete:
                    // BaseController-ConcreteController, baseController-concreteController
                    var findCharr = txtFind.Text.ToCharArray();
                    string replacement;
                    if (text[pos] == Char.ToUpper(findCharr[0]))
                    {
                        replacement = txtReplace.Text.FirstCharToUpper();
                    }
                    else if (text[pos] == Char.ToLower(findCharr[0]))
                    {
                        replacement = txtReplace.Text.FirstCharToLower();
                    }
                    else
                    {
                        continue;
                    }
                    docView.TextBuffer?.Delete(new Microsoft.VisualStudio.Text.Span(pos + span.Start, txtFind.Text.Length));
                    docView.TextBuffer?.Insert(pos + span.Start.Position, replacement);
                    pos += replacement.Length;
                }
            }
            while (true);

        }
    }
}